<template>
  <div class="parallax" @scroll="onScrollChange">
    <!--缓慢移动区-->
    <div class="parallax-slow" :style="{ top: slowTop }">
      <slot name="parallax-slow"></slot>
    </div>
    <!--正常移动区-->
    <div class="parallax-content z-index-2">
      <slot></slot>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Parallax',
  data() {
    return {
      SPEED_DIFF: 2, // 速度差(正常移动端移动100px，缓冲移动区移动 100/2 = 50px)
      parallaxScroll: 0 // 页面滚动值
    };
  },
  methods: {
    onScrollChange($event) {
      this.parallaxScroll = $event.target.scrollTop;
    }
  },
  computed: {
    // 返回 slow 距离顶部的距离
    slowTop: function() {
      // 当前页面滑动的距离 / 速度差 = 缓慢移动区应该移动的距离
      // 当前页面的滑动距离 - 缓慢移动区应该懂的距离 = 缓慢移动区用来缓冲掉 scroll 的值
      return this.parallaxScroll - this.parallaxScroll / this.SPEED_DIFF + 'px';
    }
  }
};
</script>

<style lang="scss" scoped>
.parallax {
  position: absolute;
  width: 100%;
  height: 100%;
  overflow: hidden;
  overflow-y: auto;

  &-slow {
    width: 100%;
    position: relative;
  }

  &-content {
    width: 100%;
    position: relative;
  }

  .z-index-2 {
    z-index: 2;
  }
}
</style>
